package com.zhangxiaofanfan.hotcode.second;


import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked">34. 在排序数组中查找元素的第一个和最后一个位置</a>
 *
 * @date 2024-06-29 10:39:00
 * @author zhangxiaofanfan
 */
public class HotCode065 {
    public static void main(String[] args) {
        HotCode065 hotCode = new HotCode065();
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 8;
        System.out.println(Arrays.toString(hotCode.searchRange(nums, target)));
    }

    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        int left = 0, right = nums.length - 1, mid, targetIndex = -1, leftIndex, rightIndex;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                targetIndex = mid;
                break;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (targetIndex == -1) {
            return new int[] {-1, -1};
        }
        // 查找左边界
        if (nums[0] >= target) {
            leftIndex = 0;
        } else {
            left = 0;
            right = targetIndex;
            while (left < right) {
                mid = left + ((right - left) >> 1);
                if (nums[mid] >= target) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            leftIndex = left;
        }
        // 查找右边界
        if (nums[nums.length - 1] <= target) {
            rightIndex = nums.length - 1;
        } else {
            left = targetIndex;
            right = nums.length;
            while (left < right) {
                mid = left + ((right - left) >> 1);
                if (nums[mid] > target) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            rightIndex = left - 1;
        }
        return new int[] {leftIndex, rightIndex};
    }

}
